<template>
  <div class="residence-query">
    <!-- 查询表单 -->
    <el-card class="search-card" shadow="never">
      <template #header>
        <span>查询条件</span>
      </template>
      
      <el-form
        ref="queryFormRef"
        :model="queryForm"
        :inline="true"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="身份证号">
              <el-input
                v-model="queryForm.personIdCard"
                placeholder="请输入身份证号"
                clearable
                maxlength="18"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请类型">
              <el-select
                v-model="queryForm.applicationType"
                placeholder="请选择申请类型"
                clearable
                style="width: 100%"
              >
                <el-option label="全部" value="" />
                <el-option label="首次申请" value="1" />
                <el-option label="换领" value="2" />
                <el-option label="补领" value="3" />
                <el-option label="注销" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请状态">
              <el-select
                v-model="queryForm.applicationStatus"
                placeholder="请选择申请状态"
                clearable
                style="width: 100%"
              >
                <el-option label="全部" value="" />
                <el-option label="待审核" value="0" />
                <el-option label="审核通过" value="1" />
                <el-option label="审核拒绝" value="2" />
                <el-option label="已完成" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="申请日期">
              <el-date-picker
                v-model="queryForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" @click="handleQuery" :loading="loading">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 查询结果 -->
    <el-card class="result-card" shadow="never">
      <template #header>
        <div class="result-header">
          <span>查询结果</span>
        </div>
      </template>
      
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column prop="applicationId" label="申请ID" width="120" align="center" />
        <el-table-column prop="idCard" label="身份证号" width="180" align="center" />
        <el-table-column prop="name" label="姓名" width="100" align="center" />
        <el-table-column prop="certificateType" label="证件类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getCertificateTypeTag(row.certificateType)">
              {{ formatCertificateType(row.certificateType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applicationType" label="申请类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getApplicationTypeTag(row.applicationType)">
              {{ formatApplicationType(row.applicationType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applicationReason" label="申请原因" min-width="150" show-overflow-tooltip />
        <el-table-column prop="applicationDate" label="申请日期" width="120" align="center" />
        <el-table-column prop="applicationStatus" label="申请状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.applicationStatus)">
              {{ formatStatus(row.applicationStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
        <el-table-column label="操作" width="240" align="center" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                @click="handleViewDetail(row)"
                link
              >
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <el-button 
                v-if="row.applicationStatus === 1" 
                type="success" 
                size="small" 
                @click="handleApprove(row)"
              >
                <el-icon><Check /></el-icon>
                通过
              </el-button>
              <el-button 
                v-if="row.applicationStatus === 1" 
                type="danger" 
                size="small" 
                @click="handleReject(row)"
              >
                <el-icon><Close /></el-icon>
                拒绝
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="申请详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="身份证号">
            {{ currentDetail.idCard }}
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ currentDetail.name }}
          </el-descriptions-item>
          <el-descriptions-item label="证件类型">
            <el-tag :type="getCertificateTypeTag(currentDetail.certificateType)">
              {{ formatCertificateType(currentDetail.certificateType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请类型">
            <el-tag :type="getApplicationTypeTag(currentDetail.applicationType)">
              {{ formatApplicationType(currentDetail.applicationType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请状态">
            <el-tag :type="getStatusTag(currentDetail.applicationStatus)">
              {{ formatStatus(currentDetail.applicationStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请日期" :span="2">
            {{ currentDetail.applicationDate }}
          </el-descriptions-item>
          <el-descriptions-item label="申请原因" :span="2">
            {{ currentDetail.applicationReason }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ currentDetail.remark || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ currentDetail.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间" :span="2">
            {{ currentDetail.updateTime }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  Refresh, 
  View,
  Check,
  Close
} from '@element-plus/icons-vue'
import axios from 'axios'

// API基础URL
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8088'

// 响应式数据
const loading = ref(false)
const queryFormRef = ref()
const detailDialogVisible = ref(false)
const currentDetail = ref(null)

// 查询表单
const queryForm = reactive({
  personIdCard: '',
  applicationType: '',
  applicationStatus: '',
  dateRange: []
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])

// 模拟数据
const mockData = [
  {
    applicationId: 'RC2024010001',
    personIdCard: '110101199001011234',
    personName: '张三',
    certificateType: '3', // 居住证
    applicationType: '1', // 首次申请
    applicationReason: '在本市工作需要办理居住证',
    applicationDate: '2024-01-15',
    applicationStatus: '1', // 审核通过
    remark: '材料齐全',
    createTime: '2024-01-15 09:30:00',
    updateTime: '2024-01-16 14:20:00'
  },
  {
    applicationId: 'RC2024010002',
    personIdCard: '110101199002022345',
    personName: '李四',
    certificateType: '4', // 临时居住证
    applicationType: '3', // 补领
    applicationReason: '居住证遗失需要补办',
    applicationDate: '2024-01-16',
    applicationStatus: '0', // 待审核
    remark: '已提交遗失声明',
    createTime: '2024-01-16 10:15:00',
    updateTime: '2024-01-16 10:15:00'
  },
  {
    applicationId: 'RC2024010003',
    personIdCard: '110101199003033456',
    personName: '王五',
    certificateType: '3', // 居住证
    applicationType: '2', // 换领
    applicationReason: '居住证即将到期需要换领',
    applicationDate: '2024-01-17',
    applicationStatus: '3', // 已完成
    remark: '已制证完成',
    createTime: '2024-01-17 11:00:00',
    updateTime: '2024-01-20 16:30:00'
  }
]

// 查询数据
const handleQuery = async () => {
  loading.value = true
  
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      console.log('用户未登录，跳过自动查询')
      loading.value = false
      return
    }

    // 构建查询参数 - 只发送必要参数和有值的可选参数
    const params = {
      certificateType: '居住证',  // 必传参数
      pageNum: pagination.currentPage,  // 必传参数
      pageSize: pagination.pageSize,    // 必传参数
    }

    // 只添加有值的可选参数
    if (queryForm.personIdCard && queryForm.personIdCard.trim()) {
      params.idCard = queryForm.personIdCard.trim()
    }
    if (queryForm.applicationType) {
      params.applicationType = parseInt(queryForm.applicationType)
    }
    if (queryForm.applicationStatus) {
      params.applicationStatus = parseInt(queryForm.applicationStatus)
    }

    console.log('发送查询请求，参数:', params)
    console.log('请求地址:', `${API_BASE_URL}/certificate/query`)

    // 调用后端查询接口
    const response = await axios.get(`${API_BASE_URL}/certificate/query`, {
      params,
      headers: { 'token': token }
    })

    console.log('查询响应:', response.data)

    const result = response.data
    if (result.status === 200) {
      tableData.value = result.data || []
      pagination.total = result.total || 0
      if (tableData.value.length > 0) {
        ElMessage.success('查询成功')
      } else {
        ElMessage.info('暂无数据')
      }
    } else {
      ElMessage.error(result.msg || '查询失败')
      tableData.value = []
      pagination.total = 0
    }

  } catch (error) {
    console.error('查询出错:', error)
    
    if (error.response) {
      console.error('响应错误:', error.response.status, error.response.data)
      const errorMsg = error.response.data?.msg || `服务器错误 (${error.response.status})`
      ElMessage.error(errorMsg)
    } else if (error.request) {
      console.error('网络请求失败:', error.request)
      ElMessage.error('无法连接到服务器，请检查网络连接或确认后端服务已启动')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error('查询失败: ' + error.message)
    }
    
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 重置查询
const handleReset = () => {
  queryFormRef.value?.resetFields()
  pagination.currentPage = 1
  handleQuery()
}

// 查看详情
const handleViewDetail = (row) => {
  currentDetail.value = row
  detailDialogVisible.value = true
}

// 审批通过
const handleApprove = async (row) => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('用户未登录')
      return
    }

    const approvalData = {
      id: row.id,
      applicationStatus: 2  // 2表示审核通过
    }

    console.log('发送审批通过请求，参数:', approvalData)

    const response = await axios.put(`${API_BASE_URL}/certificate/approval`, approvalData, {
      headers: { 'token': token }
    })

    console.log('审批响应:', response.data)

    if (response.data.status === 200) {
      ElMessage.success('审批通过成功')
      // 刷新数据
      handleQuery()
    } else {
      ElMessage.error(response.data.msg || '审批失败')
    }
  } catch (error) {
    console.error('审批出错:', error)
    ElMessage.error('审批失败: ' + (error.response?.data?.msg || error.message))
  }
}

// 审批拒绝
const handleReject = async (row) => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('用户未登录')
      return
    }

    const approvalData = {
      id: row.id,
      applicationStatus: 3  // 3表示审核拒绝
    }

    console.log('发送审批拒绝请求，参数:', approvalData)

    const response = await axios.put(`${API_BASE_URL}/certificate/approval`, approvalData, {
      headers: { 'token': token }
    })

    console.log('审批响应:', response.data)

    if (response.data.status === 200) {
      ElMessage.success('审批拒绝成功')
      // 刷新数据
      handleQuery()
    } else {
      ElMessage.error(response.data.msg || '审批失败')
    }
  } catch (error) {
    console.error('审批出错:', error)
    ElMessage.error('审批失败: ' + (error.response?.data?.msg || error.message))
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  handleQuery()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  handleQuery()
}

// 格式化证件类型
const formatCertificateType = (type) => {
  const types = {
    '3': '居住证',
    '4': '临时居住证'
  }
  return types[type] || '未知'
}

// 获取证件类型标签样式
const getCertificateTypeTag = (type) => {
  const tags = {
    '3': 'success',
    '4': 'warning'
  }
  return tags[type] || 'info'
}

// 格式化申请类型
const formatApplicationType = (type) => {
  const types = {
    '1': '首次申请',
    '2': '换领',
    '3': '补领',
    '4': '注销'
  }
  return types[type] || '未知'
}

// 获取申请类型标签样式
const getApplicationTypeTag = (type) => {
  const tags = {
    '1': 'primary',
    '2': 'success',
    '3': 'warning',
    '4': 'danger'
  }
  return tags[type] || 'info'
}

// 格式化状态
const formatStatus = (status) => {
  const statuses = {
    '0': '待审核',
    '1': '审核通过',
    '2': '审核拒绝',
    '3': '已完成'
  }
  return statuses[status] || '未知'
}

// 获取状态标签样式
const getStatusTag = (status) => {
  const tags = {
    '0': 'warning',
    '1': 'success',
    '2': 'danger',
    '3': 'info'
  }
  return tags[status] || 'info'
}

// 组件挂载时查询数据
onMounted(() => {
  handleQuery()
})
</script>

<style lang="scss" scoped>
.residence-query {
  .search-card {
    margin-bottom: 20px;
    border: 1px solid #e4e7ed;
    
    :deep(.el-card__header) {
      background-color: #f5f7fa;
      border-bottom: 1px solid #e4e7ed;
      padding: 15px 20px;
      
      span {
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .result-card {
    border: 1px solid #e4e7ed;
    
    :deep(.el-card__header) {
      background-color: #f5f7fa;
      border-bottom: 1px solid #e4e7ed;
      padding: 15px 20px;
      
      .result-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        span {
          font-weight: 600;
          color: #303133;
        }
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }

  .detail-content {
    .el-descriptions {
      :deep(.el-descriptions__label) {
        font-weight: 600;
        color: #606266;
        width: 120px;
      }
      
      :deep(.el-descriptions__content) {
        color: #303133;
      }
    }
  }

  .action-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
    align-items: center;
    flex-wrap: nowrap;
    
    .el-button {
      margin: 0;
      min-width: auto;
      padding: 5px 12px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .residence-query {
    .search-card {
      :deep(.el-form) {
        .el-row {
          .el-col {
            margin-bottom: 10px;
          }
        }
      }
    }
    
    .result-card {
      :deep(.el-table) {
        font-size: 12px;
      }
      
      .pagination-container {
        text-align: center;
        
        .el-pagination {
          justify-content: center;
        }
      }
    }
  }
}
</style>